package com.android.dialer.extendboard;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;

import com.android.dialer.extendboard.R;

import java.util.List;
import java.util.Random;

public class SpeedDialAdapter extends RecyclerView.Adapter<SpeedDialAdapter.ViewHolder> {

    private final String TAG = "SpeedDialAdapter";

    public interface OnItemClickListener {
        void onEditClick(SpeedDialItem item);
        void onDeleteClick(SpeedDialItem item);
    }

    private List<SpeedDialItem> items;
    private Context context;
    private OnItemClickListener listener;

    public SpeedDialAdapter(List<SpeedDialItem> items, Context context, OnItemClickListener listener) {
        this.items = items;
        this.context = context;
        this.listener = listener;
    }

    private Bitmap loadContactAvatar(String photoUri) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            java.io.InputStream inputStream = contentResolver.openInputStream(Uri.parse(photoUri));
            if (inputStream != null) {
                return BitmapFactory.decodeStream(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_speed_dial, parent, false);
        return new ViewHolder(view);
    }

    private Bitmap generateInitialBitmap(String name, int width, int height) {
        String initial = getInitial(name);

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(getRandomColor());
        canvas.drawRect(0, 0, width, height, backgroundPaint);

        Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(30);
        textPaint.setTextAlign(Paint.Align.CENTER);

        Rect bounds = new Rect();
        textPaint.getTextBounds(initial, 0, initial.length(), bounds);
        float x = width / 2f;
        float y = height / 2f + (bounds.bottom - bounds.top) / 2f - bounds.bottom;

        canvas.drawText(initial, x, y, textPaint);

        return bitmap;
    }

    private String getInitial(String name) {
        if (name != null && !name.isEmpty()) {
            String[] parts = name.split(" ");
            if (parts.length > 0) {
                Log.d(TAG, "getInitial: " + parts[0].substring(0, 1).toUpperCase());
                return parts[0].substring(0, 1).toUpperCase();
            }
        }
        return "";
    }

    private int getRandomColor() {
        Random random = new Random();
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return Color.rgb(red, green, blue);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SpeedDialItem item = items.get(position);
        holder.name.setText(item.getName());

        Log.d(TAG, "onBindViewHolder: position: " + position + ", item: " + item.toString());

        if (item.getAvatar().isEmpty()) {
            holder.avatar.setImageBitmap(generateInitialBitmap(item.getName(), 50, 50));
        } else {
            Bitmap bitmap = loadContactAvatar(item.getAvatar());
            if (bitmap != null) {
                holder.avatar.setImageBitmap(bitmap);
            } else {
                holder.avatar.setImageBitmap(generateInitialBitmap(item.getName(), 50, 50));
            }
        }

        if (item.isActive()) {
            holder.editIcon.setVisibility(View.VISIBLE);
            holder.deleteIcon.setImageResource(R.drawable.delete);
            holder.editIcon.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onEditClick(item);
                }
            });
            holder.deleteIcon.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onDeleteClick(item);
                }
            });
        } else {
            holder.editIcon.setVisibility(View.GONE);
            holder.deleteIcon.setImageResource(R.drawable.add);
            holder.deleteIcon.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onEditClick(item);
                }
            });
        }
    }

    public void updateItem(SpeedDialItem item, int position) {
        items.set(position, item);
        notifyItemChanged(position);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        ImageView avatar;
        ImageView editIcon;
        ImageView deleteIcon;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            avatar = itemView.findViewById(R.id.avatar);
            editIcon = itemView.findViewById(R.id.editIcon);
            deleteIcon = itemView.findViewById(R.id.deleteIcon);
        }
    }
}